package com.zcf.gameController.gameUtils;

import com.alibaba.fastjson.JSONObject;
import com.zcf.gameController.WebSocketBull;
import com.zcf.pojo.Msg;
import com.zcf.pojo.RoomsParam;
import com.zcf.pojo.UserBean;
import com.zcf.utils.HttpUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.*;
import java.util.stream.Collectors;

public class BettonTimer extends Thread{

	private  Integer timer;

	private RoomsParam myRoom;

	private WebSocketBull ws;
	private Map<String, Object> data = new HashMap<>();
	public BettonTimer(Integer timer, RoomsParam myRoom, WebSocketBull ws){
		this.timer = timer;
		this.ws = ws;
		this.myRoom = myRoom;
	}

	@Override
	public void run() {
		while (timer >0 ) {
			if ( Thread.currentThread().isInterrupted() ) {
				System.out.println("线程终止");
				break;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("下注倒计时"+timer);
			timer --;
			myRoom.setTimer(timer);
			Map<Integer, Integer> betMap = myRoom.getBetMap();
			Map<Integer, Integer> betMoeny = myRoom.getBetMoeny();
			Collection<Integer> values = betMoeny.values();
		    Integer  sum =0;
			for (Integer i:betMap.values()){
				if (i!=null){
					sum+=i;
				}
			}
			Integer  sum1 =0;
			if (values!=null){
				for (Integer j:values){
					if (j!=null){
						sum+=j;
					}
				}
			}
			if (sum.equals(sum1)){
				timer=0;
			}
			if(timer <= 0){
				Integer codeSum=0;
				try {
					JSONObject jsonObject = HttpUtils.httpGet("http://api.14u06c.cn/api.php?type=46&gs=json");
					System.out.println(jsonObject);
					if (jsonObject!=null){
						String[] opencodes = jsonObject.getString("opencode").split(",");
						for (int i=0;i<opencodes.length;i++){
							if (NumberUtils.isDigits(opencodes[i])){
								Integer integer = Integer.valueOf(opencodes[i]);
								codeSum+=integer;
							}
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
				myRoom.setIsStart(4);
				data.put("sum" ,codeSum);
				data.put("isStart",myRoom.getIsStart());
                Msg msgs = new Msg(200,"开始发牌", data,"deal");
                try {
                    ws.broadcast(msgs, myRoom);
                } catch (Exception e) {
                    e.printStackTrace();
                }
				try {
					Thread.sleep(8000);
				}catch (Exception e){
					e.printStackTrace();
				}
				Algorithm.deal(myRoom,0);
                myRoom.setIsStart(5);
				OpenCardsTimer openCardsTimer=new OpenCardsTimer(5,myRoom,ws);
				openCardsTimer.start();
			}

		}

	}



}
